package com.teacher.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.teacher.common.CommonResult;
import com.teacher.common.JwtTokenUtil;
import com.teacher.common.utils.HttpClientUtil;
import com.teacher.pojo.dto.wx.WechatUserUpdateDto;
import com.teacher.pojo.dto.wx.WxLoginDto;
import com.teacher.pojo.dto.wx.WxSignDto;
import com.teacher.pojo.entity.WechatUser;
import com.teacher.mapper.WechatUserMapper;
import com.teacher.pojo.vo.WxLoginVo;
import com.teacher.security.entity.security.RedisUserInfo;
import com.teacher.security.service.IRedisService;
import com.teacher.service.IWechatUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangzhuohang
 * @since 2024-03-14
 */
@Service
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements IWechatUserService {

    @Value("${jwt.expiration}")
    private Long expiration;

    @Autowired
    private IRedisService iRedisService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private HttpServletRequest httpServletRequest;
    
    @Autowired
    private WechatUserMapper wechatUserMapper;

    public final static String appId = "wxb4632b40969646bb";
    public final static String secret = "8806f39cc7880a535c8b9522f9fc8d4c";
    // 微信小程序授权登录请求的网址
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";


    @Override
    public CommonResult<WxLoginVo> wxLogin(WxLoginDto wxLoginDto) {
        // 接收前端参数
        String code = wxLoginDto.getCode();  //code
        System.out.println("小程序登录");
        if (StringUtils.isEmpty(code)) {
            return CommonResult.failed("code不能为空");
        }
        //需要拿客户端获得的code换取openId
        String url = String.format(WX_LOGIN_URL, appId, secret, code);
        //调用微信api授权
        String data = HttpClientUtil.doGet(url);
        System.out.println("请求结果：" + data);
        //解析返回的json字符串属性	类型	说明
        JSONObject jsonObject = JSONObject.parseObject(data);
        String openId = jsonObject.getString("openid");
        if (StringUtils.isEmpty(openId)){
            return CommonResult.failed(data.toString());
        }
        //数据库查找是否已经是小程序用户,不是就加入
        WechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, openId));
        if (ObjectUtil.isEmpty(wechatUser)){
            wechatUser = new WechatUser();
            BeanUtil.copyProperties(wxLoginDto,wechatUser);
            wechatUser.setCreditScore((float) 5.0);
            wechatUser.setOpenId(openId);
            int insert = wechatUserMapper.insert(wechatUser);
            if (insert<1){
                return CommonResult.failed("数据库新建用户失败");
            }
        }
        System.out.println("新用户加入数据库老用户直接返回 openid："+openId);
        WxLoginVo wxLoginVo = new WxLoginVo();
        BeanUtil.copyProperties(wechatUser,wxLoginVo);

        String token = jwtTokenUtil.generateToken(openId);
        wxLoginVo.setToken(token);

        RedisUserInfo redisUserInfo = new RedisUserInfo();
        redisUserInfo.setToken(token);
        iRedisService.set(wechatUser.getOpenId(), JSONUtil.toJsonStr(redisUserInfo));
        iRedisService.expire(wechatUser.getOpenId(), expiration);

        return CommonResult.success(wxLoginVo);
    }

    @Override
    public CommonResult<WxLoginVo> wxLoginTest(String openId) {
        WechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, openId));
        if (ObjectUtil.isEmpty(wechatUser)){
            return CommonResult.failed("无此用户");
        }
        String token = jwtTokenUtil.generateToken(openId);
        WxLoginVo wxLoginVo = new WxLoginVo();
        BeanUtil.copyProperties(wechatUser,wxLoginVo);
        wxLoginVo.setToken(token);
        RedisUserInfo redisUserInfo = new RedisUserInfo();
        redisUserInfo.setToken(token);
        iRedisService.set(wechatUser.getOpenId(), JSONUtil.toJsonStr(redisUserInfo));
        iRedisService.expire(wechatUser.getOpenId(), expiration);
        return CommonResult.success(wxLoginVo);
    }

    @Override
    public CommonResult<String> updateInfo(WechatUserUpdateDto dto) {
        WechatUser wechatUser = new WechatUser();
        BeanUtil.copyProperties(dto,wechatUser);
        int i = wechatUserMapper.updateById(wechatUser);
        if (i<1){
            return CommonResult.failed("更新失败");
        }
        return CommonResult.success("更新成功");
    }

    @Override
    public CommonResult<String> updatePhoneNumber(String phoneNumber) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        LambdaUpdateWrapper<WechatUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WechatUser::getPhoneNumber,phoneNumber);
        updateWrapper.eq(WechatUser::getOpenId,openid);
        int update = wechatUserMapper.update(null, updateWrapper);
        if (update<1){
            return CommonResult.failed("更新电话失败");
        }
        return CommonResult.success("更新电话成功");
    }

    @Override
    public CommonResult<String> updateSchool(String school) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        LambdaUpdateWrapper<WechatUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WechatUser::getSchoolName,school);
        updateWrapper.eq(WechatUser::getOpenId,openid);
        int update = wechatUserMapper.update(null, updateWrapper);
        if (update<1){
            return CommonResult.failed("更新学校失败");
        }
        return CommonResult.success("更新学校成功");
    }

    @Override
    public CommonResult<String> updateName(String name) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        LambdaUpdateWrapper<WechatUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WechatUser::getName,name);
        updateWrapper.eq(WechatUser::getOpenId,openid);
        int update = wechatUserMapper.update(null, updateWrapper);
        if (update<1){
            return CommonResult.failed("更新名称失败");
        }
        return CommonResult.success("更新名称成功");
    }

    @Override
    public CommonResult<String> updateImgUrl(String imgUrl) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        LambdaUpdateWrapper<WechatUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WechatUser::getImgUrl,imgUrl);
        updateWrapper.eq(WechatUser::getOpenId,openid);
        int update = wechatUserMapper.update(null, updateWrapper);
        if (update<1){
            return CommonResult.failed("更新头像失败");
        }
        return CommonResult.success("更新头像成功");
    }

    @Override
    public CommonResult<String> signInfo(WxSignDto wxSignDto) {
        WechatUserUpdateDto wechatUserUpdateDto = new WechatUserUpdateDto();
        BeanUtil.copyProperties(wxSignDto,wechatUserUpdateDto);
        return updateInfo(wechatUserUpdateDto);
    }
}
